package com.kmxd.ams.core.license.verify.service;

import com.kmxd.ams.core.license.verify.config.LicenseVerifyProperties;
import com.kmxd.ams.core.license.verify.listener.ACustomVerifyListener;
import com.kmxd.ams.core.license.verify.listener.ParamType;
import com.kmxd.ams.core.license.verify.model.LicenseAuthInfo;
import com.kmxd.ams.core.license.verify.model.LicenseVerifyManager;
import com.kmxd.ams.license.core.content.LicenseContents;
import com.kmxd.ams.license.core.model.LicenseExtraParam;
import com.kmxd.ams.license.core.model.LicenseResult;
import com.kmxd.ams.license.core.service.AServerInfos;
import com.kmxd.ams.license.core.utils.Base64Utils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@AllArgsConstructor
public class LicenseVerifyService {

  /**
   * 获取申请码与授权信息
   *
   * @return 申请码
   */
  public LicenseAuthInfo licenseAuthInfo() {
    // 申请码
    LicenseExtraParam extraParam = AServerInfos.getServer().getServerInfos(null);
    extraParam.setParams(getAppParams());
    String encode = Base64Utils.encodeLicenseExtraParam(extraParam);
    // 证书中携带的个性信息
    Map<String, Object> result = null;
    if (LicenseContents.PARAMS != null) {
      result = new HashMap<>();
      for (ACustomVerifyListener<?> customVerifyListener :
          ACustomVerifyListener.getCustomListenerList()) {
        ParamType paramType = customVerifyListener.paramType();
        result.put(paramType.getKey(), LicenseContents.PARAMS.get(paramType.getKey()));
      }
    }
    return LicenseAuthInfo.builder()
        .code(encode)
        .beginTime(LicenseContents.BEGIN_TIME) // 证书开始时间
        .afterTime(LicenseContents.AFTER_TIME) // 证书结束时间
        .params(result) // 证书中包含的其他数据
        .build();
  }

  /**
   * 更新证书
   *
   * @param license 证书base64
   * @throws Exception 更新失败
   */
  public void updateLicense(String license) throws Exception {
    LicenseVerifyProperties properties = new LicenseVerifyProperties();
    properties.setLicenseCode(license);
    LicenseResult licenseResult = LicenseVerifyManager.simpleInstall(properties.getVerifyParam());
    if (!licenseResult.getResult()) {
      throw new Exception("更新失败，请检查证书的合法性" + licenseResult.getMessage());
    }
  }

  /** 获取所有认证参数 */
  private Map<String, Object> getAppParams() {
    List<ACustomVerifyListener<?>> list = ACustomVerifyListener.getCustomListenerList();
    Map<String, Object> params = new HashMap<>();
    for (ACustomVerifyListener<?> aCustomVerifyListener : list) {
      params.put(
          aCustomVerifyListener.paramType().getKey(),
          aCustomVerifyListener.paramType().getValueType());
    }
    return params;
  }
}
